import { useEffect, useState } from 'react';
import {
  Video,
  Clock,
  HardDrive,
  TrendingUp,
  Play,
  Pause,
  CheckCircle,
  AlertCircle,
  ArrowRight,
  Cpu,
  MemoryStick,
  Database,
  Network,
  RefreshCw,
} from 'lucide-react';
import { useAppSelector, useAppDispatch } from '@/store';
import { setBreadcrumbs } from '@/store/slices/uiSlice';
import { invoke } from '@tauri-apps/api/core';
import { useSystemInfo } from '@/hooks/useSystemInfo';
import { useVideoStats } from '@/hooks/useVideoStats';
import { useActiveTasks } from '@/hooks/useActiveTasks';

const Dashboard: React.FC = () => {
  const dispatch = useAppDispatch();
  const { user } = useAppSelector(state => state.auth);
  const { systemInfo, isLoading: systemLoading, refreshSystemInfo } = useSystemInfo();
  const { stats, isLoading: statsLoading, refreshStats } = useVideoStats();
  const { tasks, isLoading: tasksLoading, pauseTask, resumeTask, cancelTask } = useActiveTasks();

  useEffect(() => {
    dispatch(setBreadcrumbs([{ label: '仪表板' }]));
  }, [dispatch]);

  // 实时数据统计
  const dashboardStats = [
    {
      id: 1,
      title: '处理视频总数',
      value: stats.totalProcessed.toLocaleString(),
      change: `+${stats.weeklyTrend}%`,
      icon: Video,
      color: 'text-blue-600',
      bgColor: 'bg-blue-50',
      description: '累计处理的视频文件数量',
    },
    {
      id: 2,
      title: '节省时间',
      value: `${Math.floor(stats.totalSavedTime / 60)}h ${stats.totalSavedTime % 60}m`,
      change: '+8%',
      icon: Clock,
      color: 'text-green-600',
      bgColor: 'bg-green-50',
      description: '通过批量处理节省的总时间',
    },
    {
      id: 3,
      title: '存储空间节省',
      value: `${(stats.totalSavedSpace / 1024).toFixed(1)}GB`,
      change: '+23%',
      icon: HardDrive,
      color: 'text-purple-600',
      bgColor: 'bg-purple-50',
      description: '通过压缩节省的总存储空间',
    },
    {
      id: 4,
      title: '处理效率',
      value: `${stats.successRate}%`,
      change: '+5%',
      icon: TrendingUp,
      color: 'text-orange-600',
      bgColor: 'bg-orange-50',
      description: '任务成功率',
    },
  ];

  // 系统状态统计
  const systemStats = [
    {
      id: 1,
      title: 'CPU使用率',
      value: `${systemInfo.cpuUsage.toFixed(1)}%`,
      icon: Cpu,
      color: systemInfo.cpuUsage > 80 ? 'text-red-600' : 'text-blue-600',
      bgColor: systemInfo.cpuUsage > 80 ? 'bg-red-50' : 'bg-blue-50',
      status: systemInfo.cpuUsage > 80 ? 'high' : 'normal',
    },
    {
      id: 2,
      title: '内存使用',
      value: `${systemInfo.memoryUsage.percentage}%`,
      icon: MemoryStick,
      color: systemInfo.memoryUsage.percentage > 80 ? 'text-red-600' : 'text-green-600',
      bgColor: systemInfo.memoryUsage.percentage > 80 ? 'bg-red-50' : 'bg-green-50',
      status: systemInfo.memoryUsage.percentage > 80 ? 'high' : 'normal',
      description: `${systemInfo.memoryUsage.used}GB / ${systemInfo.memoryUsage.total}GB`,
    },
    {
      id: 3,
      title: '磁盘使用',
      value: `${systemInfo.diskUsage.percentage}%`,
      icon: Database,
      color: systemInfo.diskUsage.percentage > 90 ? 'text-red-600' : 'text-purple-600',
      bgColor: systemInfo.diskUsage.percentage > 90 ? 'bg-red-50' : 'bg-purple-50',
      status: systemInfo.diskUsage.percentage > 90 ? 'high' : 'normal',
      description: `${systemInfo.diskUsage.used}GB / ${systemInfo.diskUsage.total}GB`,
    },
    {
      id: 4,
      title: '网络状态',
      value: systemInfo.networkStatus === 'online' ? '在线' : '离线',
      icon: Network,
      color: systemInfo.networkStatus === 'online' ? 'text-green-600' : 'text-red-600',
      bgColor: systemInfo.networkStatus === 'online' ? 'bg-green-50' : 'bg-red-50',
      status: systemInfo.networkStatus === 'online' ? 'normal' : 'error',
    },
  ];

  const handleRefreshAll = async () => {
    await Promise.all([refreshSystemInfo(), refreshStats()]);
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'processing':
        return <Play className='w-4 h-4 text-blue-600' />;
      case 'queued':
        return <Pause className='w-4 h-4 text-yellow-600' />;
      case 'completed':
        return <CheckCircle className='w-4 h-4 text-green-600' />;
      case 'failed':
        return <AlertCircle className='w-4 h-4 text-red-600' />;
      default:
        return <Clock className='w-4 h-4 text-gray-600' />;
    }
  };

  const getStatusText = (status: string) => {
    const statusMap: Record<string, string> = {
      processing: '处理中',
      queued: '排队中',
      completed: '已完成',
      failed: '失败',
      paused: '暂停',
    };
    return statusMap[status] || status;
  };

  return (
    <div className='dashboard-page'>
      {/* Welcome Section */}
      <div className='welcome-section'>
        <div className='flex items-center justify-between'>
          <div>
            <h1>欢迎回来，{user?.username || '用户'}！</h1>
            <p>今天是处理视频的好日子，让我们开始工作吧！</p>
          </div>
          <div className='flex items-center space-x-4'>
            <button 
              onClick={handleRefreshAll}
              className='btn btn-outline flex items-center space-x-2'
              disabled={systemLoading || statsLoading}
            >
              <RefreshCw className='w-4 h-4' />
              <span>刷新数据</span>
            </button>
            <div className='welcome-icon hidden md:block'>
              <Video size={96} />
            </div>
          </div>
        </div>
      </div>

      {/* 视频处理统计 */}
      <div className='stats-grid'>
        {dashboardStats.map(stat => {
          const IconComponent = stat.icon;
          return (
            <div key={stat.id} className='stat-card'>
              <div className='stat-header'>
                <div className={`stat-icon ${stat.bgColor} ${stat.color}`}>
                  <IconComponent />
                </div>
                <span className='stat-change'>{stat.change}</span>
              </div>
              <h3 className='stat-value'>{stat.value}</h3>
              <p className='stat-title'>{stat.title}</p>
              {stat.description && (
                <p className='stat-description'>{stat.description}</p>
              )}
            </div>
          );
        })}
      </div>

      {/* 系统状态监控 */}
      <div className='content-card'>
        <div className='card-header'>
          <h2>系统状态监控</h2>
          <div className='flex items-center space-x-2'>
            <span className='text-sm text-gray-600'>最后更新: {new Date().toLocaleTimeString()}</span>
            <button 
              onClick={refreshSystemInfo}
              className='btn btn-outline btn-sm'
              disabled={systemLoading}
            >
              <RefreshCw className='w-3 h-3' />
            </button>
          </div>
        </div>
        
        <div className='stats-grid grid-cols-2 lg:grid-cols-4'>
          {systemStats.map(stat => {
            const IconComponent = stat.icon;
            return (
              <div key={stat.id} className='stat-card'>
                <div className='stat-header'>
                  <div className={`stat-icon ${stat.bgColor} ${stat.color}`}>
                    <IconComponent />
                  </div>
                  <span className={`status-indicator ${
                    stat.status === 'normal' ? 'bg-green-400' : 
                    stat.status === 'high' ? 'bg-yellow-400' : 
                    'bg-red-400'
                  }`} />
                </div>
                <h3 className='stat-value'>{stat.value}</h3>
                <p className='stat-title'>{stat.title}</p>
                {stat.description && (
                  <p className='stat-description'>{stat.description}</p>
                )}
              </div>
            );
          })}
        </div>
      </div>

      {/* Main Content Grid */}
      <div className='main-content'>
        {/* Active Tasks */}
        <div className='content-card'>
          <div className='card-header'>
            <h2>当前任务</h2>
            <div className='flex items-center space-x-2'>
              <span className='text-sm text-gray-600'>
                活跃任务: {tasks.filter(t => t.status === 'processing' || t.status === 'queued').length}
              </span>
              <a href='/batch-process' className='view-all'>查看全部 <ArrowRight size={16} /></a>
            </div>
          </div>

          {tasks.length > 0 ? (
            <div>
              {tasks.slice(0, 5).map(task => (
                <div key={task.id} className='task-item'>
                  <div className='task-status'>{getStatusIcon(task.status)}</div>
                  <div className='task-details'>
                    <div className='flex items-center justify-between'>
                      <p className='task-name'>{task.name}</p>
                      <div className='task-actions'>
                        {task.status === 'processing' && (
                          <button 
                            onClick={() => pauseTask(task.id)}
                            className='btn btn-outline btn-xs'
                            title='暂停任务'
                          >
                            暂停
                          </button>
                        )}
                        {task.status === 'paused' && (
                          <button 
                            onClick={() => resumeTask(task.id)}
                            className='btn btn-outline btn-xs'
                            title='恢复任务'
                          >
                            恢复
                          </button>
                        )}
                        {(task.status === 'processing' || task.status === 'queued' || task.status === 'paused') && (
                          <button 
                            onClick={() => cancelTask(task.id)}
                            className='btn btn-outline btn-xs text-red-600'
                            title='取消任务'
                          >
                            取消
                          </button>
                        )}
                      </div>
                    </div>
                    <div className='task-meta'>
                      <span>{getStatusText(task.status)}</span>
                      <span className='separator'>•</span>
                      <span>{task.eta}</span>
                      <span className='separator'>•</span>
                      <span>{task.currentPhase}</span>
                    </div>
                    {(task.status === 'processing' || task.status === 'paused') && (
                      <div className='task-progress'>
                        <div className='progress-bar'>
                          <div 
                            className='progress-fill'
                            style={{ width: `${task.progress}%` }}
                          />
                        </div>
                        <div className='progress-text'>{task.progress.toFixed(1)}%</div>
                      </div>
                    )}
                    {task.status === 'failed' && task.error && (
                      <div className='task-error'>
                        <span className='error-text'>{task.error}</span>
                      </div>
                    )}
                  </div>
                </div>
              ))}
              {tasks.length > 5 && (
                <div className='task-more'>
                  <a href='/batch-process' className='view-more'>
                    还有 {tasks.length - 5} 个任务...
                  </a>
                </div>
              )}
            </div>
          ) : (
            <div className='empty-state'>
              <Clock />
              <p>暂无活跃任务</p>
              <p className='empty-subtitle'>开始处理视频后，任务将在此显示</p>
            </div>
          )}
        </div>

        {/* Recent Files */}
        <div className='content-card'>
          <div className='card-header'>
            <h2>最近文件</h2>
            <a href='#' className='view-all'>查看全部 <ArrowRight size={16} /></a>
          </div>
          <div className='empty-state'>
            <Video />
            <p>暂无最近文件</p>
            <p className='empty-subtitle'>上传或处理视频后，文件将在此显示</p>
          </div>
        </div>
      </div>

      {/* Quick Actions */}
      <div className='content-card'>
        <div className='card-header'>
          <h2>快速操作</h2>
        </div>
        <div className='quick-actions'>
          <div className='action-grid'>
            <a href='/video-tools/format-converter' className='action-button'>
              <Video size={20} />
              视频转换
            </a>
            <a href='/video-tools/video-compressor' className='action-button secondary'>
              <HardDrive size={20} />
              视频压缩
            </a>
            <a href='/video-tools/audio-extractor' className='action-button secondary'>
              <Play size={20} />
              音频提取
            </a>
            <a href='/batch-process' className='action-button secondary'>
              <TrendingUp size={20} />
              批量处理
            </a>
          </div>
        </div>
      </div>
    </div>
  );
};

import './styles.less';

export default Dashboard;
